#include "DownloadWindow.h"
#include <iostream>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QPushButton>
#include <QTextStream>
#include <QFile>
#include <QFileInfo>
#include <QUrl>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QLabel>
#include <QProcess>
#include <QEventLoop>
#include <QTimer>

namespace bap {

	DownloadWindow::DownloadWindow(QWidget *parent ){
		this->setMinimumWidth(360);
		QVBoxLayout* mainlayout = new QVBoxLayout();

		m_MessageLabel = new QLabel("Downloading ... ", this);
		QLabel* MessageLabel = new QLabel(this);
		m_ProgressBar = new QProgressBar(this);
		m_ProgressBar->setOrientation(Qt::Horizontal);
		mainlayout->addWidget(MessageLabel);
		mainlayout->addWidget(m_ProgressBar);
		mainlayout->addWidget(m_MessageLabel);

		QWidget* widget = new QWidget(this);
		this->setCentralWidget(widget);
		widget->setLayout(mainlayout);

		m_AccessManager = new QNetworkAccessManager(this);
		connect(m_AccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ReplyFinishedSlot(QNetworkReply*)));


		QFile sfile(":/commonwidget.qss");
		sfile.open(QFile::ReadOnly);
		QString mainwindowqss = sfile.readAll();
		sfile.close();
		this->setStyleSheet(mainwindowqss);

		m_Timer= new QTimer(this);
		connect(m_Timer, SIGNAL(timeout()), this, SLOT(timerUpDate()));

		m_Timer->start(1000);
	}

	DownloadWindow::~DownloadWindow()
	{
	}

	void DownloadWindow::onDownloadProgress(qint64 bytesSent, qint64 bytesTotal)
	{
		m_ProgressBar->setMaximum(bytesTotal);
		m_ProgressBar->setValue(bytesSent);
	}

	void DownloadWindow::onReadyRead()
	{
		m_File->write(m_Reply->readAll());
		m_MessageLabel->setText("Downloading "+m_File->fileName());
	}

	void DownloadWindow::onfinished()
	{
		m_File->close();
	}

	void DownloadWindow::timerUpDate()
	{
		//_sleep(10000);
		QStringList urllist;
#ifdef WIN32
		QString fntfilename = QString::fromStdString("fnt-" + m_version + ".zip");
		urllist.append("http://bap.cebsit.ac.cn/FNT/"+ fntfilename);
		urllist.append("http://bap.cebsit.ac.cn/FNT/7z.exe");
		urllist.append("http://bap.cebsit.ac.cn/FNT/7z.dll");

		Download(urllist);

		QProcess process;
		process.execute("../7z.exe", QStringList({ "x","-y","-o../","../"+ fntfilename }));
		process.startDetached("fnt-tracer");
#else
        QString fntfilename="";
        if (QSysInfo::prettyProductName().left(6)=="Ubuntu"){
            fntfilename = QString::fromStdString("fnt-" + m_version + "-ubuntu.zip");
        }else if (QSysInfo::prettyProductName().left(6)=="Fedora")
        {
            fntfilename = QString::fromStdString("fnt-" + m_version + "-fedora.zip");
        }else if(QSysInfo::prettyProductName().left(5)=="macOS"){
            fntfilename = QString::fromStdString("fnt-" + m_version + "-macos.zip");
        }
        std::cout<<QSysInfo::prettyProductName().toStdString()<<fntfilename.toStdString()<<std::endl;
        urllist.append("http://bap.cebsit.ac.cn/FNT/" + fntfilename);
        Download(urllist);
        QProcess process;
        process.execute("unzip", QStringList({ "-o","-d../","../" + fntfilename }));
        process.startDetached("./fnt-tracer");
#endif
		m_Timer->stop();
		this->close();
	}

	void DownloadWindow::showEvent(QShowEvent * event)
	{

	}

	void DownloadWindow::Download(QStringList list)
	{
		for (auto str : list) {
			QUrl url(str);
			QFileInfo fileInfo = url.path();
			m_File = new QFile("../"+fileInfo.fileName());
			m_File->open(QIODevice::WriteOnly);

			m_Request.setUrl(url);
			m_Reply = m_AccessManager->get(m_Request);
			connect(m_Reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onDownloadProgress(qint64, qint64)));
			connect(m_Reply, SIGNAL(finished()), this, SLOT(onfinished()));
			connect((QObject *)m_Reply, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
			QEventLoop eventLoop;
			connect(m_AccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
			eventLoop.exec();
		}
	}

	void DownloadWindow::ReplyFinishedSlot(QNetworkReply*reply) {
		QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
		QByteArray bytes = reply->readAll();
		reply->deleteLater();
		//m_File->close();
	}

}
